# 导入相关库和模块
from config.logging import logger
from services.database_manager import databaseManager
from dotenv import load_dotenv
import os
from datetime import datetime
import string
import random
import aiofiles
from models.picture import Picture
from typing import List, Dict, Union, Any
import pandas as pd
# 定义服务类
class UploadApiService:
    def __init__(self, db, user_info = None):
        self.db = db
        self.db_manager = databaseManager(self.db)
        self.user_info = user_info if user_info else {}
        load_dotenv()

    async def image_list(self, page, limit)-> Dict[str, Union[List[Any], Any]]:
        """
        获取图片列表
        """
        query = self.db.query(Picture).filter(Picture.deleted_at.is_(None))
        lists = self.db_manager.paginate_query(query, page, limit)
        data = [self.db_manager.convert_dict_keys(menu.to_dict()) for menu in lists] if lists else []
        return {"list": data, "total": query.count()}

    async def upload_mode(self, file, file_type=None):
        mode = os.getenv('UPLOAD_MODE')
        if file_type is None:
            # 如果为None则是图片
            upload_functions = {
                'local': self.upload_image_local,
                'qiniu': self.upload_image_qiniu,
                'oss' : self.upload_image_oss,
            }
            if file.content_type.startswith('image/'):
                upload_func = upload_functions.get(mode)
                if upload_func:
                    return await upload_func(file)
                else:
                    raise Exception(f"不支持的上传模式 {mode}")
            else:
                raise Exception("不支持的文件类型")

        if file_type == 'file':
            upload_functions = {
                'local': self.upload_file_local,
                # 'qiniu': self.upload_file_qiniu,
                # 'oss' : self.upload_file_oss,
            }
            logger.info(f"打印文件类型{file.content_type}")
            if file.content_type.startswith('application/'):
                upload_func = upload_functions.get(mode)
                if upload_func:
                    return await upload_func(file)

    async def upload_file_local(self, file):
        """
        @desc 上传excel文件到本地
        """
        current_date = datetime.now().strftime("%Y%m%d")
        upload_root = os.path.join(os.getenv('UPLOAD_FILE'))
        path = os.path.join(upload_root, current_date)
        os.makedirs(path, exist_ok=True)
        random_filename = self.generate_random_string()
        file_extension = os.path.splitext(file.filename)[1]
        full_file_name = random_filename + file_extension
        file_path = os.path.join(path, full_file_name)
        async with aiofiles.open(file_path, 'wb') as out_file:
            while content := await file.read(1024):  # 使用 await 读取文件内容
                await out_file.write(content)  # 使用 await 写入文件内容
        content = pd.read_excel(file_path)
        logger.info(f"打印文件{content}")
        return True
    async def upload_detail(self, detailId: int, uploadType: str):
        """
        获取图片详情
        """
        if uploadType == 'image':
            res = self.db_manager.detail_query(Picture, {"id":detailId,"deleted_at": None}, need=True)
            if res is None:
                return {"error": "资源不存在"}
            return self.db_manager.convert_dict_keys(res) if res else {}
        else:
            raise Exception("暂不支持")

    async def upload_delete(self, detailId: int, uploadType: str):
        """
        删除图片 从不同的库删除不同的文件
        uploadType: image, file, video
        """
        if uploadType == 'image':
            res = self.db_manager.detail_update(Picture, {"id":detailId}, {"deleted_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")})
            if res is None:
                return {"error": "资源不存在"}
        else:
            raise Exception("暂不支持")
        return True

    async def upload_image_local(self, file):
        # 生成当前年月日目录
        current_date = datetime.now().strftime("%Y%m%d")
        # 构建保存路径
        upload_root = os.path.join(os.getenv('UPLOAD_IMAGE_FILE'))
        path = os.path.join(upload_root, current_date)
        os.makedirs(path, exist_ok=True)
        random_filename = self.generate_random_string()
        file_extension = os.path.splitext(file.filename)[1]
        full_file_name = random_filename + file_extension

        # 构建保存路径
        file_path = os.path.join(path, full_file_name)
        # 异步保存文件
        async with aiofiles.open(file_path, 'wb') as out_file:
            while content := await file.read(1024):  # 使用 await 读取文件内容
                await out_file.write(content)  # 使用 await 写入文件内容
        access_url = f"/upload/images/{current_date}/{full_file_name}"

        # 记录日志
        logger.info(f"文件 {file.filename} 已成功上传到 {file_path}")
        data = {
            "user_id": self.user_info['id'],
            "user_type": 1,
            "img_url": access_url,
            "type": 'local',
            "file_type": 1,
            "name": full_file_name,
            "ext": file_extension[1:],
            "file_size": round(file.size/(1024*1024), 2) ,
        }
        res = self.db_manager.create_entry(Picture, data)

        return self.db_manager.convert_dict_keys(res)

    async def upload_image_qiniu(self, file):
        raise Exception("暂不支持")

    async def upload_image_oss(self, file):
        raise Exception("暂不支持")

    def generate_random_string(self, length=12):
        """
        随机字符串生成
        """
        letters = string.ascii_letters + string.digits
        return ''.join(random.choice(letters) for _ in range(length))
